# -*- coding:utf-8 -*-
"""
@Author : 审心
@Time : 2023/3/21 17:10
请求封装
"""
import requests
import sys
from config import data as config
from common.logger.log import log_


class Request:
    def __init__(self, methods: str, uri: str, params=None, req_title="", json_data=None, req_is_log=False,
                 err_is_log=True,
                 req_param_is_log=True):
        """
        初始化 post 请求
        :param methods: 请求方法
        :param uri: 请求uri
        :param params: 请求参数字典
        :param req_title: 请求标题
        :param req_is_log: 请求内容是否输出日志
        :param err_is_log: 发生错误是否输出日志
        """
        self.methods = methods
        self.uri = uri
        self.params = params
        self.json_data = json_data
        self.req_title = req_title
        self.req_is_log = req_is_log
        self.err_is_log = err_is_log
        self.req_param_is_log = req_param_is_log

    def send(self) -> dict:
        # noinspection PyBroadException
        res = None
        try:
            if self.methods == 'get':
                res = requests.get(config.get("api.baseUrl") + self.uri, self.params, json=self.json_data)
            elif self.methods == 'post':
                res = requests.post(config.get("api.baseUrl") + self.uri, self.params, json=self.json_data)
            else:
                raise RuntimeError("当前不支持该请求方法 : " + self.methods)
            if res.status_code != 200:
                raise RuntimeError("请求 失败 status_code : " + str(res.status_code))
        except:
            if self.err_is_log:
                print("MSG : " + str(sys.exc_info()[0]))
            raise RuntimeError("请求 失败")
        result = {}
        self.req_log(res)
        if res.headers['Content-Type'] == 'text/plain;charset=UTF-8':
            result = res.json()
        else:
            raise RuntimeError("暂未涉及的响应正文类型, 请追加相关处理")
        return result

    def req_log(self, res):
        """
        打印请求日志
        :param res: 响应
        :return:
        """
        if self.req_is_log:
            params_log = f"params : {self.params} \n" if self.req_param_is_log else ""
            log_.info(f"\n<------------------ 请求【{self.req_title}】开始 ------------------>\n" +
                      "=================request===================\n" +
                      f"body: {res.request.body} \n" +
                      f"headers: {res.request.headers} \n" +
                      f"URI : {self.uri} \n" +
                      params_log +
                      "=================response===================\n" +
                      f"headers : {res.headers} \n" +
                      f"content : {res.content} \n" +
                      f"text : {res.text} \n" +
                      f"json : {res.json()} \n" +
                      f"encoding : {res.encoding} \n" +
                      f"history : {res.history} \n" + f"<----------------- 请求【{self.req_title}】结束 ----------------->")


if __name__ == '__main__':
    print(Request("post", "public/robot/test", {"test": 123}, "测试", True).send())
